package com.szgr.baoyin.activity;

import android.app.Dialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.lbsapi.tools.CoordinateConverter;
import com.baidu.lbsapi.tools.Point;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
//import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
//import com.baidu.mapapi.overlayutil.TransitRouteOverlay;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.baidu.mapapi.search.core.RouteNode;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.nplatform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.guide.BYGuideActivity;
import com.szgr.baoyin.guide.Gps;
import com.szgr.baoyin.guide.PositionUtil;
import com.szgr.baoyin.model.MyProtectItem;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DateUtils;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.RLog;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的维保
 */
public class ProtectActivity extends BaseActivity implements BaiduMap.OnMapClickListener {

    private Dialog dialog;
    private boolean firstLogin = true;
    private BaiduMap baiduMap;
    private LocationClient mLocationClient;
    private MapView protectView;
    private RoutePlanSearch routePlanSearch;
    private PlanNode stNode;
    private String authinfo;
    private String mSDCardPath = null;
    private static final String APP_FOLDER_NAME = "Baoyin";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private BitmapDescriptor startIcon;
    private BitmapDescriptor endIcon;
    private LatLng currentLatLng;   //起点
    private LatLng endLatLng;       //终点
    private String currentPlace;    //起点名称
    private String endPlace;        //终点名称
    private boolean hasStart = false;
    private boolean hasEnd = false;
    private EditText et_search;
    private GeoCoder geoCoder;
    private PlanNode enNode;
    private boolean firstIn = true;
    private double ppp = 39.997015;
    private boolean hasProtect;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2009:
                    mLocationClient.requestLocation();

//                    MyLocationData locData = new MyLocationData.Builder()
////                .accuracy(bdLocation.getRadius())
////                .direction(bdLocation.getDirection())
//                            .latitude(ppp)
//                            .longitude(116.346071)
//                            .build();
//                    baiduMap.setMyLocationData(locData);
//                    MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,true,mCurrentMarker);
//                    baiduMap.setMyLocationConfigeration(config);

//                    locationCurrentSite(ppp,116.346071);
//                    baiduMap.setMyLocationEnabled(true);
//                    MyLocationData locationData = new MyLocationData.Builder().latitude(ppp).longitude(116.346071).build();
//                    locationBitmap.position(new LatLng(ppp,116.346071));
//
//                    baiduMap.clear();
//                    baiduMap.addOverlay(locationBitmap);
//                    baiduMap.setMyLocationData(locationData);
//                    baiduMap.setMyLocationEnabled(false);
                    ppp = ppp + 0.0001;
//                    MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(new LatLng(ppp,116.346071));
//                    baiduMap.animateMapStatus(status);

//                    mHandler.sendEmptyMessageDelayed(2009, 2 * 1000);
                    break;
                case 234:
                    hasProtect = false;
                    break;
                case 235:
                    hasProtect = true;
                    break;
                case 208:
                    firstLogin = true;
                    break;
                case 678:
//                    getMyProtect();
                    DialogUtils.hideLoadingDialog();
                    Intent onceIntent = new Intent(ProtectActivity.this, UrgencyFixActivity.class);
                    onceIntent.putExtra("where", currentMode);
                    onceIntent.putExtra("isOncePro", true);//是否首次维保
                    startActivity(onceIntent);
                    break;
                case 680:
                    DialogUtils.hideLoadingDialog();
                    ToastUtils.showToast((String) msg.obj);
                    break;
            }
        }
    };
    private BitmapDescriptor mCurrentMarker;
    private MarkerOptions locationBitmap;
    private BDLocationListener bdLocationListener;
    private ArrayList<MyProtectItem> data;
    private PoiSearch poiSearch;
    private String currentMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_protect);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {

        baiduMap.setMyLocationEnabled(false);
        routePlanSearch.destroy();
        poiSearch.destroy();
        baiduMap.clear();
        baiduMap = null;
        protectView.onDestroy();
        protectView = null;

        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        protectView.onResume();

        if (mLocationClient != null) {
            mLocationClient.start();
        }
//        mHandler.sendEmptyMessage(2009);

        hasStart = true;
        hasEnd = false;

        getMyProtect();
    }

    @Override
    public void onPause() {
        super.onPause();
        protectView.onPause();
//        mHandler.removeMessages(2009);
        mLocationClient.stop();
    }


    @Override
    public void initActionBar() {
        actionBarTitle.setText("维保");
    }

    @Override
    public void initView() {
        if (initDirs()) {
            initNavi();
        }

        mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.mycar);
        et_search = (EditText) findViewById(R.id.protect_et_result);
        Button btn_order = (Button) findViewById(R.id.protect_order);
        btn_order.setOnClickListener(this);
        findViewById(R.id.protect_fix).setOnClickListener(this);
        findViewById(R.id.protect_btn_search).setOnClickListener(this);

        protectView = (MapView) findViewById(R.id.protect_baidu_map);

        baiduMap = protectView.getMap();

        //定位
        mLocationClient = new LocationClient(this);
        initLocation();
        bdLocationListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                System.out.println("-----loc---->" + bdLocation.getLatitude() + ";" + bdLocation.getLongitude());
                if (baiduMap != null) {
                    String city = bdLocation.getCity();
                    String addrStr = bdLocation.getAddrStr();
                    //当前的经纬度

                    currentLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                    currentPlace = addrStr;

                    System.out.println("----->" + city + "," + addrStr);
                    stNode = PlanNode.withLocation(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));
                    LatLng point = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());

                    locationBitmap = new MarkerOptions()
                            .position(point)
                            .icon(mCurrentMarker);
//                    baiduMap.clear();
//                    baiduMap.addOverlay(locationBitmap);


                    locationCurrentSite(bdLocation.getLatitude(), bdLocation.getLongitude());
                }
            }
        };
        mLocationClient.registerLocationListener(bdLocationListener);
        mLocationClient.start();

        /**
         * 线路规划
         */
        routePlanSearch = RoutePlanSearch.newInstance();
        routePlanSearch.setOnGetRoutePlanResultListener(listener);

        startIcon = BitmapDescriptorFactory.fromResource(R.drawable.icon_point);
        endIcon = BitmapDescriptorFactory.fromResource(R.drawable.icon_point);

//        baiduMap.setOnMapClickListener(this);
        baiduMap.setMyLocationEnabled(true);

        //实例化一个地理编码查询对象
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                //获取点击的坐标地址
            }

            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                System.out.println("----address---->" + result.getLocation().longitude + "," + result.getLocation().latitude);
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    ToastUtils.showToast("抱歉，未能找到结果");
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    endLatLng = result.getLocation();
                    LatLng fromLatlng = gcj02ToBd09(currentLatLng);
                    LatLng toLatlng = gcj02ToBd09(endLatLng);
                    routeplanToNavi(BNRoutePlanNode.CoordinateType.GCJ02,
                            currentPlace, fromLatlng.longitude, fromLatlng.latitude,
                            et_search.getText().toString().trim(), toLatlng.longitude, toLatlng.latitude);
                }
            }
        });

        judgeProtect();

        poiSearch = PoiSearch.newInstance();
        poiSearch.setOnGetPoiSearchResultListener(poiListener);
    }

    /**
     * 判断是否能免费维保
     */
    private void judgeProtect() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_FREE_ZIGE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("---result--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            String result = datas.getString("result");
                            if ("1".equals(result)) {
                                mHandler.obtainMessage(208).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener() {
        public void onGetPoiResult(PoiResult result) {
            //获取POI检索结果
            PoiOverlay overlay = new MyPoiOverlay(baiduMap);
            //设置overlay可以处理标注点击事件
            baiduMap.setOnMarkerClickListener(overlay);
            //设置PoiOverlay数据
            overlay.setData(result);
            //添加PoiOverlay到地图中
            overlay.addToMap();
            overlay.zoomToSpan();
        }

        public void onGetPoiDetailResult(PoiDetailResult result) {
            //获取Place详情页检索结果
        }
    };

    private class MyPoiOverlay extends PoiOverlay {
        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            return true;
        }
    }

    private void getMyProtect() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_MY_PROTECT,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("------>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONArray order_maintenance_list = datas.getJSONArray("$order_maintenance_list");
                            Gson gson = new Gson();
                            data = gson.fromJson(order_maintenance_list.toString(), new TypeToken<List<MyProtectItem>>() {
                            }.getType());
                            if (data != null && data.size() == 0) {
                                mHandler.sendEmptyMessage(234);
                            } else {
                                mHandler.sendEmptyMessage(235);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    /**
     * 百度坐标系转成GPS坐标系
     *
     * @param c
     * @param
     */
    private LatLng gcj02ToBd09(LatLng c) {
        Gps gps = PositionUtil.bd09_To_Gcj02(c.latitude, c.longitude);
        return new LatLng(gps.getWgLat(), gps.getWgLon());
    }

//    @Override
//    public void onMapDoubleClick(LatLng latLng) {
////        baiduMap.clear();
//        if(!hasStart || hasEnd ) {
//            currentLatLng = latLng;
//            MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(startIcon);
//            hasStart = true;
//            hasEnd = false;
//            baiduMap.addOverlay(markerOptions);
//        }else{
//            endLatLng = latLng;
//            MarkerOptions endOptions = new MarkerOptions().position(latLng).icon(endIcon);
//            hasEnd = true;
//            baiduMap.addOverlay(endOptions);
//        }
//    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (hasStart) {
            baiduMap.clear();
            endLatLng = latLng;
            System.out.println("--start--->lat:" + latLng.latitude + ",long:" + latLng.longitude);
            MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(endIcon);

//            hasStart = true;
            hasEnd = true;
            baiduMap.addOverlay(markerOptions);

//            stNode = PlanNode.withLocation(latLng);
            enNode = PlanNode.withLocation(latLng);
            routePlanSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
        } else {
            endLatLng = latLng;
            System.out.println("--end--->lat:" + latLng.latitude + ",long:" + latLng.longitude);
            MarkerOptions endOptions = new MarkerOptions().position(latLng).icon(endIcon);
            hasEnd = true;
            baiduMap.addOverlay(endOptions);

            enNode = PlanNode.withLocation(latLng);
            routePlanSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
        }
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }


    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(
                Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    private OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult result) {
            //
            System.out.println("---进来了-->");
//            route = result.getRouteLines().get(0); //获取路线
            if (result.error == SearchResult.ERRORNO.NO_ERROR) {  //同上

                DrivingRouteOverlay overlay = new DrivingRouteOverlay(baiduMap);
//            routeOverlay = overlay;
                baiduMap.setOnMarkerClickListener(overlay);
                overlay.setData(result.getRouteLines().get(0));//overLay 为在地图上的路径 ，这里为它设置数据
                baiduMap.clear();
                overlay.addToMap();  //添加到地图
                overlay.zoomToSpan();
                DrivingRouteLine line = result.getRouteLines().get(0);

//                List<RouteNode> wayPoints = line.getWayPoints();
//                RouteNode routeNode = wayPoints.get(0);
//                currentLatLng = line.getStarting().getLocation();
//                RouteNode routeNode1 = wayPoints.get(wayPoints.size() - 1);
//                endLatLng = line.getTerminal().getLocation();
            }
        }
    };

    /**
     * 初始化定位配置信息
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 2000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        mLocationClient.setLocOption(option);
    }

    /**
     * 定位当前地位置
     *
     * @param
     */
    private void locationCurrentSite(double lat, double lon) {

        MyLocationData locData = new MyLocationData.Builder()
//                .accuracy(bdLocation.getRadius())
//                .direction(bdLocation.getDirection())
                .latitude(lat)
                .longitude(lon)
                .build();
        baiduMap.setMyLocationData(locData);

        if (firstIn) {
//            OverlayOptions options = new CircleOptions()
//                    .center(currentLatLng)
//                    .radius(20)
//                    .fillColor(0xaac7dee9)
//                    .stroke(new Stroke(3,0xff80a3d0));
////                    baiduMap.clear();
//            baiduMap.addOverlay(options);

//            poiSearch.searchNearby((new PoiNearbySearchOption())
//                    .location(currentLatLng)
//                    .keyword("饭店")
//                    .pageNum(10)
//                    .radius(30000));

            baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(19).build()));
            MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null);
            baiduMap.setMyLocationConfigeration(config);
            firstIn = false;
        } else {

            MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null);
            baiduMap.setMyLocationConfigeration(config);
//            MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(new LatLng(lat,lon));
//            baiduMap.animateMapStatus(msu);
        }

//        baiduMap.setMyLocationEnabled(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.protect_order:
                currentMode = "order";
                if (MyApplication.getmInstance().isLogin()) {
                    gotoFix(currentMode);
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.protect_fix:
                currentMode = "urgency";
                if (MyApplication.getmInstance().isLogin()) {
                    gotoFix(currentMode);
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.protect_buy_now:
//                Intent intent = new Intent(this,);
                Intent nowIntent = new Intent(this, BuyProtectActivity.class);
//                nowIntent.putExtra("where","order");//预约
                startActivity(nowIntent);
                dialog.dismiss();
                break;
            case R.id.protect_buy_next:
                dialog.dismiss();
//                startActivity(new Intent(this,RegisterActivity.class));
//                firstLogin = false;
                break;
            case R.id.protect_buy_once:
//                Intent onceIntent = new Intent(this,UrgencyFixActivity.class);
//                onceIntent.putExtra("where",currentMode);
//                onceIntent.putExtra("isOncePro",true);//是否首次维保
//                startActivity(onceIntent);
                gofixOnce("免费维保一次", DateUtils.paseDate(System.currentTimeMillis() / 1000));
                dialog.dismiss();
                break;
            case R.id.protect_btn_search:
//                PlanNode enNode = PlanNode.withLocation(new LatLng(39.963175, 116.400244));
//                routePlanSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
                if (hasEnd) {
                    LatLng fromLatlng = gcj02ToBd09(currentLatLng);
                    LatLng toLatlng = gcj02ToBd09(endLatLng);
                    routeplanToNavi(BNRoutePlanNode.CoordinateType.GCJ02,
                            currentPlace, fromLatlng.longitude, fromLatlng.latitude,
                            "", toLatlng.longitude, toLatlng.latitude);
                } else {
                    if (MyTool.isEmpty(et_search)) {
                        ToastUtils.showToast("请在输入框内输入您想到达的地点");
                        return;
                    }

                    //地理编码

                    //设置反地理编码位置坐标
                    GeoCodeOption op = new GeoCodeOption();
                    op.city("");
                    op.address(et_search.getText().toString().trim());
                    //发起反地理编码请求(经纬度->地址信息)
                    geoCoder.geocode(op);
                }
                break;
        }
    }

    private void gofixOnce(final String free, final String date) {
        DialogUtils.showLoadingDialog(this, "正在加载中...");
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_FREE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("---free--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            Object datas = jsonObject.get("datas");
                            if(datas instanceof String){
                                String datas1 = (String) datas;
                                if ("操作成功".equals(datas)) {
                                    mHandler.obtainMessage(678).sendToTarget();
                                }
                            }else if(datas instanceof JSONObject){
                                JSONObject datas2 = (JSONObject) datas;
                                String error = datas2.getString("error");
                                mHandler.obtainMessage(680,error).sendToTarget();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("brand", free);
                map.put("make_date", date);
                RLog.s("---params--->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void gotoFix(String where) {
        if (!hasProtect) {
            if (firstLogin) {
                dialog = DialogUtils.showCustomerDialog(this,
                        "尊敬的用户，您还未购买我们的维保服务，请购买后再进行操作。", "立即购买", "稍后购买", "免费维保一次",
                        this, this, this);
            } else {
                dialog = DialogUtils.showCustomerDialog(this,
                        "尊敬的用户，您还未购买我们的维保服务，请购买后再进行操作。", "立即购买", "稍后购买",
                        this, this);
            }
            dialog.show();
        } else {
            //TODO 已经购买维保
            Intent fixIntent = new Intent(this, UrgencyFixActivity.class);
            fixIntent.putExtra("where", where);
            fixIntent.putExtra("code", data);
            startActivity(fixIntent);
        }
    }

    private void initNavi() {
        BaiduNaviManager.getInstance().setNativeLibraryPath(mSDCardPath + "/BaiduNaviSDK_SO");
        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME,
                new BaiduNaviManager.NaviInitListener() {
                    @Override
                    public void onAuthResult(int status, String msg) {
                        if (0 == status) {
                            authinfo = "key校验成功!";
                        } else {
                            authinfo = "key校验失败, " + msg;
                        }
                        ProtectActivity.this.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
//                                Toast.makeText(getApplicationContext(), authinfo, Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    public void initSuccess() {
//                        Toast.makeText(getApplicationContext(), "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                    }

                    public void initStart() {
//                        Toast.makeText(getApplicationContext(), "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
                    }

                    public void initFailed() {
                        Toast.makeText(getApplicationContext(), "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
                    }
                }, null /*mTTSCallback*/);
    }

    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType, String fromPlace, double fromLong, double fromLat, String toPlace, double toLong, double toLat) {
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            case GCJ02: {
                sNode = new BNRoutePlanNode(fromLong, fromLat,
                        fromPlace, null, coType);
                eNode = new BNRoutePlanNode(toLong, toLat,
                        toPlace, null, coType);
                break;
            }
            case WGS84: {
                sNode = new BNRoutePlanNode(fromLong, fromLat,
                        fromPlace, null, coType);
                eNode = new BNRoutePlanNode(toLong, toLat,
                        toPlace, null, coType);
                break;
            }
            case BD09_MC: {
                sNode = new BNRoutePlanNode(fromLong, fromLat,
                        fromPlace, null, coType);
                eNode = new BNRoutePlanNode(toLong, toLat,
                        toPlace, null, coType);
                break;
            }
            default:
                ;
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new MyRoutePlanListener(sNode));
        }
    }


    public class MyRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public MyRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            Intent intent = new Intent(ProtectActivity.this, BYGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            startActivity(intent);
        }

        @Override
        public void onRoutePlanFailed() {
            // TODO Auto-generated method stub

        }
    }

    /**
     * 以下没用

     private BNOuterTTSPlayerCallback mTTSCallback = new BNOuterTTSPlayerCallback() {

    @Override public void stopTTS() {
    // TODO Auto-generated method stub

    }

    @Override public void resumeTTS() {
    // TODO Auto-generated method stub

    }

    @Override public void releaseTTSPlayer() {
    // TODO Auto-generated method stub

    }

    @Override public int playTTSText(String speech, int bPreempt) {
    // TODO Auto-generated method stub
    return 0;
    }

    @Override public void phoneHangUp() {
    // TODO Auto-generated method stub

    }

    @Override public void phoneCalling() {
    // TODO Auto-generated method stub

    }

    @Override public void pauseTTS() {
    // TODO Auto-generated method stub

    }

    @Override public void initTTSPlayer() {
    // TODO Auto-generated method stub

    }

    @Override public int getTTSState() {
    // TODO Auto-generated method stub
    return 0;
    }
    };

     */

}
